/**
 * Created by yl on 2016/4/28 0028.
 */
var AppService = {
  urlroot: "http://euvee.vicp.co/rest/site/",
  init: function () {
    Vue.http.options.root = this.urlroot;
    Vue.http.options.emulateHTTP = true;
    Vue.http.options.emulateJSON = true;
  },
  //初始化引入数据
  find: function (inputQuery, pagenum, pagesteps, items, success_callback, error_callback) {
    var url = this.urlroot;
    Vue.http.get(url, function (data, status, request) {
      var i = data.length;
      success_callback(data, status, request);
    }).catch(function (data, status, request) {
      if (error_callback != null) {
        error_callback(data, status, request);
      }
    });
  },
  //绑定id，删除数据
  remove: function (item, success_callback, error_callback) {
    Vue.http.delete(this.urlroot+item.id, function (data, status, request) {
      success_callback(data, status, request);
    }).catch(function (data, status, request) {
      if (error_callback != null) {
        error_callback(data, status, request);
      }
    })
  },
  //切换节点
  change: function (item, success_callback, error_callback) {
    Vue.http.get(this.urlroot+item.id+"/children", function (data, status, request) {
      success_callback(data, status, request);
    }).catch(function (data, status, request) {
        if (error_callback != null) {
          error_callback(data, status, request);
        }
      }
    );
  },
  //修改节点信息
  edit: function (item, success_callback, error_callback) {
    Vue.http.put(this.urlroot+item.id,JSON.stringify(item.content), function (data, status, request) {
      success_callback(data, status, request);
    }).catch(function (data, status, request) {
      if (error_callback != null) {
        error_callback(data, status, request);
      }
    })
  },
  //添加节点
  add: function (item, success_callback, error_callback) {
    Vue.http.post(this.urlroot,JSON.stringify(item), function (data, status, request) {
      success_callback(data, status, request);
    }).then(function (data, status, request) {
        if (error_callback != null) {
          error_callback(data, status, request);
        }
      }
    );
  }
};
var svc = Object.create(AppService);

Vue.component('itemeditor', {
  template: '#itemeditor-tpl',
  mode:"modeEdit",
  //可以使用 props 把数据传给子组件。
  // “prop” 是组件数据的一个字段，期望从父组件传下来。子组件需要显式地用 props 选项 声明 props：
  props: [
    {
    name: 'item',
    type: Object,
    twoWay: false,
    required: true
  },
    {
      name: 'mode',
      type: String
      //default: 'modeList',
    },
    {
      name: 'onSave',
      type: Function
      //required: true,
    },
    {
      name: 'onCancel',
      type: Function
    }
  ],

  data: function () {
    return {
      result: ''
    }
  },

  methods: {
    onSubmitClick: function (e) {
      console.log("onSubmitClick: inside component itemeditor"+this.item.toString());
      this.result = vm.onSave("modeEdit", this.item);
    },
    onCancelClick: function (e) {
      console.log("onCancelClick: inside component itemeditor");
      vm.onCancel();
    }
  }
});// ------end Vue.component('itemeditor'


Vue.component('itemadd', {
  template: '#itemadd-tpl',
  //可以使用 props 把数据传给子组件。
  // “prop” 是组件数据的一个字段，期望从父组件传下来。子组件需要显式地用 props 选项 声明 props：
  props: [{
    name: 'item2',
    type: Object,
    twoWay: false,
    required: true
  },
    {
      name: 'mode',
      type: String
      //default: 'modeList',
    },
    {
      name: 'onSave',
      type: Function
      //required: true,
    },
    {
      name: 'onCancel',
      type: Function
    }
  ],

  data: function () {
    return {
      result: ''
    }
  },

  methods: {
    onSubmitClick: function (e) {
      console.log("onSubmitClick: inside component itemeditor");
      this.result = vm.onSave(this.mode, this.item);
    },
    onCancelClick: function (e) {
      console.log("onCancelClick: inside component itemeditor");
      vm.onCancel();
    }
  }
});// ------end Vue.component('itemeaddview'

//Vue实例化
var vm = new Vue({
  http: {
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
  },
  el: '#res',
  data: {
    currentView: 'itemeditor',
    items: [],
    curitem: {},
    mode: 'modeList',
    modeTitle: ""
  },
  compinents: {},

  methods: {
    _find: function (inputQuery, pagenum, pagesteps) {
      var self = this;
      svc.find('', pagenum, pagesteps, this.items, function (data, status, request) {
        self.$set('items', data);
        if (self.items.length > 0) {
          self.$set("curitem", self.items[0]);
        }
      });
    },
    onRemove: function (item) {
      var self = this;
      var r = confirm("确定删除？");
      if (r == true) {
        svc.remove(item, function (data, status, request) {
            self.$set('curitem', item);
            self._find('', 1, 6);
          }
        )
      }
    },
    //切换节点信息
    onChange: function (item) {
      var self = this;
      svc.change(item, function (data, status, request) {
        self.$set('items', data);
      });
    },
    //修改节点信息
    onEdit:function(item,mode){
      var self = this;
      vm.setMode(mode);
      vm.onSave(mode,item);

    },
    /*
     onChange:function(item){
     var self=this;
     svc.change(item,function(response){
     self.$set('curitem', item);
     self.$set("items", response.data);
     self._find('', 1, 6);
     },function(response){
     self.$set("items", response.data);
     })
     },*/
    //添加节点
    onAdd: function (item) {
      var self = this;
      console.log("onSave");
      svc.add(item, function (response, textStatus) {
        self._find('', 1, 6);
        self.$set("curitem", response.item)
      }, null);
    },
    basicsearch: function(e){
      this.searchQuery = this.searchQuery.trim();
      if ((this.searchQuery).length == 0 )
      {
        document.getElementById("searchQuery").focus();
        alert("Please input search query");
      }
      this.__find(this.searchQuery, 1, 5);
    },

    advancedsearch: function(e){
      console.log("advanced search");
      console.log(e.target.tagName); // "BUTTON"
      console.log(e.targetVM === this); // true

      var inputs = new Array();
      inputs[0] = "{begintime:'";
      inputs[1] = this.begintime;
      inputs[2] = "', endtime:'";
      inputs[3] = this.endtime;
      inputs[4] = "', remotedevice:'";
      inputs[5] = this.remotedevice;
      inputs[6] = "', searchQuery:'";
      inputs[7] = this.searchQuery;
      inputs[8] = "'}";

      var inputQuery = inputs.join('');
      console.log("your input query condition is " + inputQuery);
      this.__find(inputQuery, 2, 5);
    },
    onCancel: function () {
      console.log("onCancel");
      this.setMode('modeList');
    },
    onSave: function (mode, item) {
      var self = this;
      console.log("onSave");
      if (mode == 'modeAddNew') {
        console.log("add ");
        svc.add(item, function (response, textStatus) {
          self.ready();
          self.setMode('modeList');
        }, null);
      }
      else {
        console.log("edit ");
        svc.edit(item, function (item, status, request) {
          console.log("edit ");
          self.setMode('modeList');
        });
      }
    },
    setMode: function (newmode) {
      if (this.mode != newmode) {
        this.mode = newmode;
        switch (newmode) {
          case "modeList":
            this.modeTitle = " [列表]";
            resetItem(this.curitem);
            this.curitem.id = null;
            break;
          case "modeItemView":
            this.modeTitle = " [详情]";
            break;
          case "modeEdit":
            this.modeTitle = " [编辑]";
            break;
          case "modeAddNew":
            this.modeTitle = " [新增]";
            this.currentView = "itemadd";
            break;
          default:
            this.modeTitle = "";
        }
      }
    }
  },
  ready: function () {
    this._find('', 1, 6);
  }
});

